package com.mit.wx.controller;

import com.mit.wx.entity.AutoReplyRule;
import com.mit.wx.service.AutoReplyRuleService;
import com.mit.wx.vo.BasicJsonResult;
import com.mit.wx.vo.EasyUIDataGrid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 2018/10/12 Create by 郭文梁
 * AutoReplyRuleController
 * 自动回复规则操作控制类
 *
 * @author 郭文梁
 * @date 2018/10/12
 */
@RestController
@RequestMapping("/auto-reply-rule")
@Slf4j
public class AutoReplyRuleController {
    private final AutoReplyRuleService autoReplyRuleService;

    @Autowired
    public AutoReplyRuleController(AutoReplyRuleService autoReplyRuleService) {
        this.autoReplyRuleService = autoReplyRuleService;
    }

    @GetMapping("/page")
    public EasyUIDataGrid<AutoReplyRule> page(int page, int rows) {
        long count = autoReplyRuleService.getCount();
        List<AutoReplyRule> rules = autoReplyRuleService.list(page, rows);
        return EasyUIDataGrid.of(count, rules);
    }

    @PostMapping("/create")
    public BasicJsonResult<AutoReplyRule> create(AutoReplyRule autoReplyRule) {
        AutoReplyRule result;
        try {
            result = autoReplyRuleService.save(autoReplyRule);
        } catch (Exception e) {
            return BasicJsonResult.error(1, "保存失败：" + e.getMessage());
        }
        return BasicJsonResult.ok(result);
    }

    @PostMapping("/delete")
    public BasicJsonResult<Void> delete(Integer id) {
        int result = autoReplyRuleService.delete(id);
        if (result == 1) {
            return BasicJsonResult.ok("删除成功");
        } else {
            return BasicJsonResult.error(1, "删除失败");
        }
    }
}
